package services

import (
	"fmt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"

	"github.com/jinzhu/copier"
	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetTotalIntimacyRank(r *api_models.GetTotalIntimacyRankReq) ([]*api_models.GetTotalIntimacyRankResp, error) {
	fName := "GetTotalIntimacyRank"

	intimacys, err := db_main.GetIntimacysParam(map[string]interface{}{
		"anchorid": r.Anchorid,
	}, "intimacy desc", r.Page, r.Size)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	ids := make([]int, 0)
	for idx := range intimacys {
		ids = append(ids, intimacys[idx].Uid)
	}

	resp := make([]*api_models.GetTotalIntimacyRankResp, 0)
	err = copier.Copy(&resp, &intimacys)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	anchorMap, err := s.GetAnchors(0, ids, "", 0, 0)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	for idx := range resp {
		if _, ok := anchorMap[resp[idx].Uid]; ok {
			resp[idx].User = *anchorMap[resp[idx].Uid]
		}
	}
	return resp, nil
}

func (s *Service) GetWeekIntimacyRank(r *api_models.GetWeekIntimacyRankReq) ([]*api_models.GetWeekIntimacyRankResp, error) {
	fName := "GetWeekIntimacyRank"

	intimacys, err := db_main.GetIntimacysParam(map[string]interface{}{
		"anchorid":      r.Anchorid,
		"intimacy_week": map[string]interface{}{">": 0},
	}, "intimacy_week desc", r.Page, r.Size)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	ids := make([]int, 0)
	for idx := range intimacys {
		ids = append(ids, intimacys[idx].Uid)
	}

	resp := make([]*api_models.GetWeekIntimacyRankResp, 0)
	err = copier.Copy(&resp, &intimacys)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	anchorMap, err := s.GetAnchors(0, ids, "", 0, 0)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	for idx := range resp {
		if _, ok := anchorMap[resp[idx].Uid]; ok {
			resp[idx].User = *anchorMap[resp[idx].Uid]
		}
	}
	return resp, nil
}
